package com.example.zxx.shardingsphere.algorithm;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.Collection;

/**
 * ByMonthShardingAlgorithm:根据创建时间月份分表 @Component
 *
 * @author zhangxiaoxiang
 * @date 2021/09/27
 */
@Slf4j
public class ByMonthShardingAlgorithm implements StandardShardingAlgorithm<Comparable<?>> {
    /**
     * Sharding.
     *
     * @param availableTargetNames available data sources or table names
     * @param shardingValue        sharding value
     * @return sharding result for data source or table name
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Comparable<?>> shardingValue) {
        //可以动态修改这个集合,动态创建表
        availableTargetNames.forEach((d)-> log.info("可用的数据源或表名:{}",d));
        log.info("分片值:{}", JSONUtil.toJsonStr(shardingValue));
        DateTime createTime = DateUtil.parseDateTime(shardingValue.getValue().toString());
        String chooseTable = shardingValue.getLogicTableName()+"_" + DateUtil.format(createTime, "yyyyMM");
        log.warn("选择的表:{}", chooseTable);
        return chooseTable;
    }


    /**
     * Sharding.
     *
     * @param availableTargetNames available data sources or table names
     * @param shardingValue        sharding value
     * @return sharding results for data sources or table names
     */
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Comparable<?>> shardingValue) {
        log.info("Collection<String> doSharding : " + availableTargetNames);
        return null;
    }

    @Override
    public void init() {
        log.info("初始化算法...");
    }

    @Override
    public String getType() {
        log.info("算法分片类型:CLASS_BASED");
        return "CLASS_BASED";
    }
}
